package snowflake.zk;

import lombok.extern.log4j.Log4j2;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * Created by dongyuncong on 2017/6/15.
 */
@Log4j2
public class ZkClient {

    private ZooKeeper zooKeeper = null;

    private String address;
    private int timeout = 5000;
    private Watcher watcher = new Watcher() {
        // 监控所有被触发的事件
        @Override
        public void process(WatchedEvent event) {
            System.out.println("ZooKeeper process event" + event.toString());
        }
    };

    public ZkClient(String address, int timeout) {
        this.address = address;
        this.timeout = timeout;
    }

    /**
     * 初始化ZK连接
     */
    private void initCheck() throws IOException {
        if (zooKeeper == null) {
            synchronized (this) {
                if (zooKeeper == null) {
                    this.releaseConnection();
                    zooKeeper = new ZooKeeper(this.address, this.timeout, this.watcher);
                }
            }
        }
    }

    /**
     * 关闭ZK连接
     */
    private void releaseConnection() {
        if (zooKeeper != null) {
            try {
                this.zooKeeper.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void createPersistentPath(String path, String data) throws IOException, KeeperException, InterruptedException {
        initCheck();
        if (null == zooKeeper.exists(path, false)) {
            String var = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            log.info("ZkClient createPersistentPath path:{},data:{},ret:{}", path, data, var);
        }
    }

   /* public void createPersistentPath(String path, String data) throws IOException, KeeperException, InterruptedException {
        initCheck();
        if (null != zooKeeper.exists(path, false)) {
            zooKeeper.getChildren(path, false).forEach(System.out::println);
            for (String str : zooKeeper.getChildren(path, false)) {
                zooKeeper.delete(path + "/" + str, -1);
            }

            zooKeeper.delete(path, -1);
        }
        String var = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info("ZkClient createPersistentPath path:{},data:{},ret:{}", path, data, var);
    }*/

    /**
     * 创建节点
     *
     * @param path 节点path
     * @param data 初始数据内容
     * @return
     */
    public String createPath(String path, String data) throws KeeperException, InterruptedException, IOException {
        initCheck();
        String var = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        log.info("ZkClient createPath path:{},data:{},ret:{}", path, data, var);
        return var;
    }

    /**
     * 读取指定节点数据内容
     */
    public String readData(String path, Stat stat) throws KeeperException, InterruptedException, IOException {
        initCheck();
        String res = new String(zooKeeper.getData(path, watcher, stat));
        log.info("readData:{},stat:{}", res, stat);
        return res;
    }

    /**
     * 更新指定节点数据内容
     */
    public Stat writeData(String path, String data) throws KeeperException, InterruptedException, IOException {
        initCheck();
        //-1表示匹配所有版本
        return zooKeeper.setData(path, data.getBytes(), -1);
    }
}
